import {Component, Inject, OnInit, ViewChild, ViewEncapsulation} from '@angular/core';
import {SCRIPT_LOADER, ScriptLoader} from "@core/script-loader/script-loader";
import {ActivatedRoute, Params} from "@angular/router";
import {ParentService} from "@train/parent/parent.service";
import {
  CommonPageVo, SNSResult, StudentTestAbilityScoreChartVO, StudentTestAbilityScoreVO,
  StudentTestScoreLineChartVO
} from "@interface/index";
import {SeedInfiniteScroll} from "@shared/components/infinite-scroll/seed-infinite-scroll/seed-infinite-scroll.component";

const ABILITY_CHANGE_OPTIONS = (params) => {
  console.log('params',params);
  return {
    xAxis: { //X轴
      axisTick: {
        show: false //刻度隐藏
      },
      axisLine: { //线
        lineStyle: {
          color: '#e5e5e5'
        },
      },
      axisLabel: {
        color: '#999999',
        fontSize: 12,
        interval: 0,
      },
      splitNumber: 7,
      // nameTextStyle: { //文字
      //   color: '#999999',
      //   fontSize: 12
      // },
      // data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
      data: params['date']
    },
    yAxis: {
      axisLine: {
        show: false
      },
      axisLabel: {
        color: '#999999',
        fontSize: 12
      },
      axisTick: {
        show: false
      },
      // min: 0,
      splitNumber: 2, //间隔数量
      splitLine: {
        lineStyle: {
          color: ['#e5e5e5'],
          type: 'dotted'
        }
      }
    },
    series: [{
      // data: [120, 200, 150, 80, 70, 110, 130],
      data: params['data'],
      type: 'bar',
      barWidth: 20,
      itemStyle: {
        normal: {
          color: '#d14a59',
          fontSize: 12,
          label: {
            show: true, //顶部数据显示
            position: 'top',
            color: '#333333'
          }
        }
      }
    }]
  };
};

@Component({
  selector: 'seed-ability-change',
  templateUrl: './ability-change.component.html',
  styleUrls: ['./ability-change.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class AbilityChangeComponent implements OnInit {

  public showChart: boolean = false;
  public options: Object;
  public echartsIntance: any;
  public studentId: number;
  public testModelId: number;
  public hasData: boolean = true;
  public testModeName: string;
  public chartLoadParam = {
    page: 1,
    hasPre: false,
    hasNext: false
  };
  public listLoadParam = {
    page: 1,
  };
  public studentTestAbilityScoreList: Array<StudentTestAbilityScoreVO> = [];
  @ViewChild(SeedInfiniteScroll) infiniteScroll;

  constructor(
    private activatedRoute: ActivatedRoute,
    private parentService: ParentService,
    @Inject(SCRIPT_LOADER) public scriptLoader: ScriptLoader
  ) {
    activatedRoute.params.switchMap((param: Params) => {
      this.studentId = +param['studentId'];
      this.testModelId = +param['testModelId'];
      this.eChartsPromise();
      this.studentAbilityScoreList();
      return this.activatedRoute.queryParams
    }).subscribe((params: Params) => {
      this.testModeName = params['testModeName'];
    })
  }

  /**
   * @author guoqs1331
   * @time 2018/4/17
   * @description 列表
   */
  studentAbilityScoreList() {
    const param = {
      "studentId": this.studentId,
      "testModelId": this.testModelId,
      "pageNo": this.listLoadParam.page,
      "rows": 7
    };
    this.parentService.studentAbilityScoreList(param).subscribe(res => {
      if (res['data'] && res['data']['list']) {
        this.listLoadParam.page++;
        if (this.infiniteScroll) {
          this.infiniteScroll.complete();
        }
        this.studentTestAbilityScoreList = [...this.studentTestAbilityScoreList, ...res['data']['list']];
        if (this.studentTestAbilityScoreList.length === 0) {
          this.hasData = false;
        }
        if (!res.data.hasNextPage && this.infiniteScroll) {
          this.infiniteScroll.enable(false);
        }
      }
    })
  }

  /**
   * @author guoqs1331
   * @time 2018/4/17
   * @description
   */
  eChartsPromise() {
    const eCharts = this.scriptLoader.load('echarts'),
      abilityScoreChart = this.studentAbilityScoreChart();
    Promise.all([eCharts, abilityScoreChart]).then((resArray) => {
      if (resArray['0']['0']['loaded'] && resArray['1']['data']) {
        // this.chartLoadParam.page++;
        const echartInfo = resArray['1']['data'];
        this.chartLoadParam.hasPre = echartInfo.hasNextPage;
        console.log('displayECharts',echartInfo)
        this.displayECharts(echartInfo);
      }
    })
  }

  /**
   * @author guoqs1331
   * @time 2018/4/21
   * @description 上一页
   */
  preScoreList() {
    this.chartLoadParam.page++;
    this.studentAbilityScoreChart().then(res => {
      this.chartLoadParam.hasNext = true;
      if (res.result === '0' && res.data) {
        this.chartLoadParam.hasPre = res.data.hasNextPage;
        this.displayECharts(res.data);
        //切换柱状图“上一页”，下面的成绩也要重新请求
        this.listLoadParam.page = this.chartLoadParam.page;
        this.studentAbilityScoreList();
      }
    })
  }

  /**
   * @author guoqs1331
   * @time 2018/4/21
   * @description 下一页
   */
  nextScoreList() {
    this.chartLoadParam.page--;
    if(this.chartLoadParam.page === 1){//到了最新的一页
      this.chartLoadParam.hasNext = false;
      this.chartLoadParam.hasPre = true;
    }
    this.studentAbilityScoreChart().then(res => {
      if (res.result === '0' && res.data) {
        this.displayECharts(res.data);
        //切换柱状图“下一页”，下面的成绩也要重新请求
        this.listLoadParam.page = this.chartLoadParam.page;
        this.studentAbilityScoreList();
      }
    })
  }

  /**
   * @author guoqs1331
   * @time 2018/4/17
   * @description
   */
  studentAbilityScoreChart(): Promise<SNSResult<CommonPageVo<StudentTestAbilityScoreChartVO>>> {
    const param = {
      // "studentId": 7,
      // "testModelId": +this.testModelId,
      // "pageNo": 1,
      // "rows": 7
      "studentId": this.studentId,
      "testModelId": this.testModelId,
      "pageNo": this.chartLoadParam.page,
      "rows": 7
    };
    return this.parentService.studentAbilityScoreChart(param).toPromise();
  }

  onChartInit(e) {
    this.echartsIntance = e;
  }

  /**
   * @author guoqs1331
   * @time 2018/4/17
   * @description 组织echart数据结构
   */
  displayECharts(eChartsInfo) {
    console.log('eChartsInfo', eChartsInfo);
    const scoreList = eChartsInfo['list'].reverse(), data = [], date = [];
    scoreList.forEach(item => {
      data.push(item['abilityCummulation']);
      console.log(item['testDate']);
      date.push(this.getMonthAndDay(item['testDate']));
    });
    this.showECharts({data, date});
  }

  showECharts(obj) {
    this.showChart = true;
    this.options = ABILITY_CHANGE_OPTIONS(obj);
  }


  /**
   * @author guoqs1331
   * @time 2018/4/17
   * @description 根据时间戳获取月份和日期
   */
  getMonthAndDay(dateStr) {
    const date = new Date(dateStr);
    return date.getMonth() + 1 + '-' + date.getDate();
  }

  ngOnInit() {
  }
}
